package com.example.config.properties;

import com.example.config.exception.RemoteConfigInitExcetpion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author <a href="juntao.zhang@bkjk.com">juntao.zhang</a>
 * @Description:
 * @Package com.example.config
 * @date 2017/12/13 17:48
 * @see
 */
public class RemoteProperties<K,V> extends HashMap<K,V>{

    private static final Logger LOGGER = LoggerFactory.getLogger(RemoteProperties.class);

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    private String applicationName;

    private Integer retry;

    private HashMap properties;



    public RemoteProperties(int initialCapacity, float loadFactor, String applicationName,  Integer retry) {
        super(initialCapacity, loadFactor);
        this.applicationName = applicationName;
        this.retry = retry;
    }

    public RemoteProperties(int initialCapacity, String applicationName,  Integer retry) {
        super(initialCapacity);
        this.applicationName = applicationName;
        this.retry = retry;
    }

    public RemoteProperties(String applicationName,  Integer retry) {
        this.applicationName = applicationName;
        this.retry = retry;
    }

    public RemoteProperties(Map<? extends K, ? extends V> m, String applicationName,  Integer retry) {
        super(m);
        this.applicationName = applicationName;
        this.retry = retry;
    }

    public void loadResource() {
        ResponseEntity<HashMap> forEntity = null ;
        for (int i = 0; i < retry; i++) {
            forEntity = REST_TEMPLATE.getForEntity("", HashMap.class,applicationName);
            if (forEntity.getStatusCode().is2xxSuccessful())
                break;
        }
        if (Objects.isNull(forEntity) || !forEntity.getStatusCode().is2xxSuccessful())
            throw new RemoteConfigInitExcetpion("load remote properties fail");
        HashMap body = forEntity.getBody();
        body.forEach((k,v) -> LOGGER.debug("key:{}\tvalue:{}",k,v));
        properties = body;
    }


    @Override
    public V get(Object key) {
        return (V) properties.get(key);
    }

    @Override
    public V getOrDefault(Object key, V defaultValue) {
        if (Objects.isNull(properties.get(key)))
            return defaultValue;
        return (V) properties.get(key);
    }


}
